package com.evernote.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.evernote.entity.NoteBook;
import com.evernote.entity.User;
import com.evernote.service.NoteBookService;
import com.evernote.service.UserService;

/**
 * Servlet implementation class DoRegister
 */
@WebServlet("/DoRegister")
public class DoRegister extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoRegister() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("utf-8");
		
		boolean flag = false;
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		String msg = "";
		
		User u = new User();
		NoteBook nb = new NoteBook();
		
		UserService us = new UserService();
		NoteBookService nbs = new NoteBookService();
		u.setUsername(username);
		u.setPassword(password);
		if(!us.isExist(u)) {//判断用户是否存在
			if(us.addUser(u) != 0) {//添加用户
				int id = us.findIdByUsername(u);
				u.setId(id);
				nb.setUid(id);
				nb.setName("默认");
				if(nbs.addDefaultNotebook(nb) != 0) {//添加默认笔记本
					msg = "注册成功";
					flag = true;
				} else {
					msg = "添加失败";
				}
			} else {
				msg = "注册失败";
			}
		} else {
			msg = "用户已存在";
		}
		request.setAttribute("msg", msg);
		if(flag) {
			request.getRequestDispatcher("WEB-INF/jsp/login.jsp").forward(request, response);
		} else {
			request.getRequestDispatcher("WEB-INF/jsp/register.jsp").forward(request, response);
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
